package mypackage;

import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.DatagramConnection;
import mypackage.stream.RecvStream;
import mypackage.stream.SendStream;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.RadioInfo;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

/**
 * A class extending the MainScreen class, which provides default standard
 * behavior for BlackBerry GUI applications.
 */
public final class EchoScreen extends MainScreen
{
    private ButtonField startButton;

    private static long _tStart;

    private static RichTextField _logField = new RichTextField();

    private static boolean log = true;

    private RecvStream mRecvStream;
    private SendStream mSendStream;

    private EditField addressField;

    private DatagramConnection mConnection;

    private HorizontalFieldManager hManager;
    
    private VerticalFieldManager vManager;

    /**
     * Creates a new MyScreen object
     */
    public EchoScreen()
    {
        // Set the displayed title of the screen
        setTitle("Echo");
        
        hManager = new HorizontalFieldManager();
        vManager = new VerticalFieldManager();

        addressField = new EditField();
        add(addressField);

        startButton = new ButtonField("Start");
        startButton.setRunnable(new Runnable()
        {
            public void run()
            {
                startEcho(addressField.getText().trim());
            }
        });

        ButtonField logButton = new ButtonField("log");
        logButton.setRunnable(new Runnable()
        {
            public void run()
            {
                log = !log;
            }
        });

        ButtonField stopButton = new ButtonField("stop");
        stopButton.setRunnable(new Runnable()
        {
            public void run()
            {
                if (mConnection != null)
                {
                    try
                    {
                        mConnection.close();
                    }
                    catch (IOException e)
                    {
                        log("Connection close ecxeption:" + e.toString());
                        e.printStackTrace();
                    }
                }
            }
        });

        vManager.add(startButton);
        vManager.add(logButton);
        vManager.add(stopButton);
        
        // add log area
        _tStart = System.currentTimeMillis();
        Font f = _logField.getFont();
        _logField.setFont(f.derive(f.getStyle(), f.getHeight() * 3 / 5));
        
        hManager.add(vManager);
        hManager.add(_logField);
        
        add(hManager);
        

    }

    private void startEcho(String address)
    {
        // new EchoPlayer().startEcho();

        try
        {
            mConnection = createDatagramCnx(38858);
        }
        catch (IOException e)
        {
            log("create connection exception:" + e.toString());
            e.printStackTrace();
        }

        mSendStream = new SendStream(address, mConnection);
        mRecvStream = new RecvStream(mConnection);
        mSendStream.start();
        
        Thread lTmpThread = new Thread(new Runnable()
        {
            public void run()
            {
                mRecvStream.start();
            }
        });
        lTmpThread.start();
    }

    public static void log(final String sValue)
    {
        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
            public void run()
            {
                long t = System.currentTimeMillis() - _tStart;
                if (log)
                {
                    _logField.insert("[" + ((t / 1000) + "." + t % 1000) + "] "
                        + sValue + "\n");
                }
            }
        });
    }

    private DatagramConnection createDatagramCnx(int port) throws IOException
    {
        String url = "datagram://:" + port;
        if ((CoverageInfo.getCoverageStatus(RadioInfo.WAF_WLAN, true) & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
        {
            url += "/ ;interface=wifi";
        }
        
        return (DatagramConnection) Connector.open(url);
    }
}
